<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-10
 * Time: 上午11:42
 */

namespace appapi\modules\v0\controllers;


use common\components\tools\Security;
use common\members\wodrow\tools\Model;
use common\models\db\Equipment;
use common\models\db\EquipmentUser;
use common\models\db\User;
use common\rewrite\deepziyu\yii_fast_api\ApiException;
use common\rewrite\deepziyu\yii_fast_api\Controller;
use common\models\db\EquipmentOperateLog;
use yii\db\Exception;

class SiteController extends Controller
{
    /**
     * site测试
     * @desc get/post
     * @param string $a moren xxx
     * @return array
     * @return string x test
     * @return string y y
     */
    public function actionIndex($a = 'xxx')
    {
        $r = [
            'a' => $a,
            'x' => 1,
            'y' => 1,
        ];
        return $r;
    }

    /**
     * 用手机发送设备操作验证码
     * @desc get/post 验证码10分钟有效;测试固定为1234,不通过手机发送
     * @param string $uuid 设备唯一标识
     * @param string $mobile 手机号
     * @param string $equipment_operate_type 设备操作类型[详见:获取设备操作类型键值对]
     * @param string $app_version_id 安装的app版本ID
     * @return array
     * @return boolean is_success 是否发送成功
     * @throws ApiException
     */
    public function actionSendEquipmentOperateCodeByMobile($uuid, $mobile, $equipment_operate_type, $app_version_id)
    {
        EquipmentOperateLog::checkUserTypeCanDo(User::findOne(['mobile' => $mobile]), $equipment_operate_type, 1);
        $key = $uuid.$mobile.$equipment_operate_type;
//        $random = rand(1000, 9999);
        $random = 1234;
        \Yii::$app->cache->set($key, $random, 600);
        # TODO send random by mobile
        $r = [
            'is_success' => true,
        ];
        \Yii::$app->equipmentInfo->equipmentOperateLog->operate_type = $equipment_operate_type;
        return $r;
    }

    /**
     * 设备手机号注册操作
     * @desc get/post
     * @param string $uuid 设备唯一标识
     * @param string $mobile 手机号
     * @param string $app_version_id 安装的app版本ID
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $code 验证码
     * @return array
     * @throws ApiException
     * @return string token 设备访问令牌
     * @return string key 设备访问秘钥
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionSignupByMobile($uuid, $mobile, $username = null, $password, $code, $app_version_id)
    {
        EquipmentOperateLog::checkUserTypeCanDo(User::findOne(['mobile' => $mobile, 'mobile_pre' => '+86']), EquipmentOperateLog::OPERATE_SIGNUP, 1);
        $key = $uuid.$mobile.EquipmentOperateLog::OPERATE_SIGNUP_SEND_CODE;
        $_code = \Yii::$app->cache->get($key);
        if (!$_code){
            throw new ApiException(201808141959, "手机号未获取注册验证码或验证码已过期");
        }
        if ($_code != $code){
            throw new ApiException(201808142000, "验证码错误");
        }
        $user = User::findOne(['or', ['mobile' => $mobile], ['username' => $username]]);
        if ($user){
            throw new ApiException(201808151143, '已存在手机号或用户名');
        }
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $user = new User();
            $user->mobile = $mobile;
            $user->username = $username;
            $user->setPassword($password);
            $user->generateToken();
            $user->created_at = $user->updated_at = Yii_BT_TIME;
            $user->auth_key = \Yii::$app->security->generateRandomString(32);
            $user->random_string = \Yii::$app->security->generateRandomString(32);
            if (!$user->save()){
                throw new Exception("用户保存失败:".Model::getModelError($user));
            }
            $equipment = Equipment::findOne(['uuid' => $uuid]);
            if (!$equipment){
                throw new ApiException(201808151331, '没有找到保存的设备信息，请确认');
            }
            $e_user = new EquipmentUser();
            $e_user->equipment_id = $equipment->id;
            $e_user->user_id = $user->id;
            $e_user->generateToken();
            $e_user->key = \Yii::$app->security->generateRandomString(32);
            $e_user->last_use_at = Yii_BT_TIME;
            $e_user->status = EquipmentUser::STATUS_ACTIVE;
            if (!$e_user->save()){
                throw new Exception("设备用户保存失败:".Model::getModelError($e_user));
            }
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw new ApiException(201808151318, $e->getMessage());
        }
        $r = [
            'token' => $e_user->token,
            'key' => $e_user->key,
        ];
        \Yii::$app->equipmentInfo->equipmentOperateLog->operate_type = EquipmentOperateLog::OPERATE_SIGNUP;
        \Yii::$app->equipmentInfo->equipmentOperateLog->for_equipment_user = $e_user->id;
        return $r;
    }

    /**
     * 重置密码or找回密码
     * @desc get/post
     * @param string $uuid 设备唯一标识
     * @param string $mobile 手机号
     * @param string $app_version_id 安装的app版本ID
     * @param string $password 密码
     * @param string $code 验证码
     * @return array
     * @throws ApiException
     * @return int is_success 重置状态
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionResetPassword($uuid, $mobile, $password = 112233, $code, $app_version_id)
    {
        $key = $uuid.$mobile.EquipmentOperateLog::RESET_PASSWORD_SEND_CODE;
        $_code = \Yii::$app->cache->get($key);
        if (!$_code){
            throw new ApiException(201810221355, "手机号未获取重置密码验证码或验证码已过期");
        }
        if ($_code != $code){
            throw new ApiException(201810221356, "验证码错误");
        }
        $user = User::findOne(['mobile' => $mobile, 'status' => User::STATUS_ACTIVE]);
        if (!$user){
            throw new ApiException(201810221359, "没有找到用户");
        }
        $user->setPassword($password);
        $equipment = Equipment::findOne(['uuid' => $uuid]);
        if (!$equipment){
            throw new ApiException(201810221415, '没有找到设备');
        }
        $e_user = EquipmentUser::findOne(['user_id' => $user->id, 'equipment_id' => $equipment->id]);
        if (!$e_user){
            $e_user->equipment_id = $equipment->id;
            $e_user->user_id = $user->id;
            $e_user->generateToken();
            $e_user->key = \Yii::$app->security->generateRandomString(32);
            $e_user->last_use_at = Yii_BT_TIME;
            $e_user->status = EquipmentUser::STATUS_ACTIVE;
            if (!$e_user->save()){
                throw new ApiException(201808151334, "设备用户保存失败:".Model::getModelError($e_user));
            }
        }
        $r = [
            'token' => $e_user->token,
            'key' => $e_user->key,
            'is_success' => 0,
        ];
        if ($user->save()){
            $r['is_success'] = 1;
        }
        \Yii::$app->equipmentInfo->equipmentOperateLog->operate_type = EquipmentOperateLog::RESET_PASSWORD;
        \Yii::$app->equipmentInfo->equipmentOperateLog->for_equipment_user = $e_user->id;
        return $r;
    }

    /**
     * 设备登陆操作
     * @desc get/post
     * @param string $uuid 设备唯一标识
     * @param string $account 手机号|身份证号|安的号
     * @param string $app_version_id 安装的app版本ID
     * @param string $password 密码
     * @return array
     * @throws ApiException
     * @return string token 设备访问令牌
     * @return string key 设备访问秘钥
     * @throws \Exception
     */
    public function actionLogin($uuid, $account, $password, $app_version_id)
    {
        /*$key = $uuid.$account.EquipmentOperateLog::OPERATE_SIGNUP_SEND_CODE;
        $_code = \Yii::$app->cache->get($key);*/
        $equipment = \Yii::$app->equipmentInfo->equipment;
        $user = User::find()->where(['mobile' => $account])->orWhere(['idcard' => $account])->one();
        if (!$user) {
            throw new ApiException(201808151700, '没有找到用户,请先注册');
        }
        if ($user->status!=User::STATUS_ACTIVE){
            throw new ApiException(201808151701, '用户不是激活状态');
        }
        $last_login_time_key = $account.EquipmentOperateLog::OPERATE_LOGIN."_lt";
        $has_login_times_key = $account.EquipmentOperateLog::OPERATE_LOGIN;
//        \Yii::$app->cache->delete($last_login_time_key);
//        \Yii::$app->cache->delete($has_login_times_key);
        $lt = \Yii::$app->cache->get($last_login_time_key);
        if ($lt&&$lt!=date("Ymd")){
            \Yii::$app->cache->delete($has_login_times_key);
        }
        $has_login_times = \Yii::$app->cache->get($has_login_times_key);
        if (!$has_login_times){
            $has_login_times = 8;
            \Yii::$app->cache->set($has_login_times_key, $has_login_times, 86400);
        }
        if ($has_login_times <= 1){
            \Yii::$app->cache->set($last_login_time_key, date("Ymd"), 86400);
            throw new ApiException(201808151806, '你今天已经登陆8次了');
        }
        if (!$user->validatePassword($password)){
            $has_login_times--;
            \Yii::$app->cache->set($has_login_times_key, $has_login_times, 86400);
            throw new ApiException(201808151702, "密码错误, 本账号今日剩余登陆次数:{$has_login_times}");
        }else{
            \Yii::$app->cache->delete($has_login_times_key);
        }
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $e_user = EquipmentUser::findOne(['equipment_id' => $equipment->id, 'user_id' => $user->id]);
            if (!$e_user)$e_user = new EquipmentUser();
            $e_user->equipment_id = $equipment->id;
            $e_user->user_id = $user->id;
            $e_user->generateToken();
            $e_user->key = \Yii::$app->security->generateRandomString(32);
            $e_user->last_use_at = Yii_BT_TIME;
            $e_user->status = EquipmentUser::STATUS_ACTIVE;
            if (!$e_user->save()){
                throw new Exception("设备用户保存失败:".Model::getModelError($e_user));
            }
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw new ApiException(201808151719, $e->getMessage());
        }
        $r = [
            'token' => $e_user->token,
            'key' => $e_user->key,
        ];
        \Yii::$app->equipmentInfo->equipmentOperateLog->operate_type = EquipmentOperateLog::OPERATE_LOGIN;
        \Yii::$app->equipmentInfo->equipmentOperateLog->for_equipment_user = $e_user->id;
        /*EquipmentOperateLog::logEquipmentOperate($uuid, EquipmentOperateLog::OPERATE_LOGIN, $app_version_id, [
            'req_account' => $account,
            'resp_data' => $r,
        ], $e_user->id);*/
        return $r;
    }
}